-- g_config 为全局变量,直接用

local util = {}

util.load_rule = function(file_name)
    local fh = io.open(g_rules_path..'/'..file_name, "r")
    local result = {}
    if fh == nil then
        return
    else
        local line_res = nil
        
        for line in fh:lines() do
            -- 以 ## 开头的行是注释,不处理; 空行,不处理;
            local from = ngx.re.find(line, "(^\\s*##)|(^\\s*$)", "jo")
            if not from then
                -- bugfix: windows中没问题,但在centos7中 line 字符串结尾包含 \r 的
                from = ngx.re.find(line, "(\r\n)$", 'jo')
                if from then
                    -- 当前 line 字符串结尾包含了 \r\n
                    line_res = string.sub(line, 1, from-1)
                else
                    from = ngx.re.find(line, "(\r|\n)$", 'jo')
                    if from then
                        -- 当前 line 字符串结尾包含了 \r 或 \n
                        line_res = string.sub(line, 1, from-1)
                    else
                        line_res = line
                    end
                end
                table.insert(result, line_res)
            end
        end
        fh:close()
    end
    return result
end

util.deny_exit = function(deny_param) 
    local return_type = type(deny_param)
    if return_type == 'number' then
        ngx.exit(deny_param)
    elseif deny_param == 'default' then
        ngx.say(g_config.default_return_html)
        ngx.exit(ngx.HTTP_NOT_ACCEPTABLE)
    else
        ngx.say(deny_param)
        ngx.exit(ngx.HTTP_NOT_ACCEPTABLE)
    end
end

util.get_client_ip = function()
    local ip = ngx.req.get_headers()["X-Real-Ip"]
    if ip == nil then
        ip = ngx.req.get_headers()["X-Forwarded-For"]
        if ip == nil then
            ip = ngx.var.remote_addr
            if ip == nil then
                ip = "unknown"
            end
        end
    end
    return ip
end

util.get_user_agent = function()
    local ua = ngx.var.http_user_agent
    if ua == nil then
        ua = "unknown"
    end
    return ua
end

-- 记录相关日志到 ngx.ctx.cls_lua_waf_log 数组中,在log_by_lua阶段写入日志文件
util.waf_log = function(log_text)
    if g_config.waf_log ~= 'on' or log_text == nil or log_text == "" then
        return
    end

    if ngx.ctx.cls_lua_waf_log == nil then
        ngx.ctx.cls_lua_waf_log = {}
    end
    
    local time = ngx.localtime()
    local ip = util.get_client_ip()
    local server_name = ngx.var.server_name
    local ua = util.get_user_agent()
    local request = ngx.var.request
    local msg = '['..time..'] '..ip..' | '..server_name..' | '..ua..' | '..request..' | '..log_text

    table.insert(ngx.ctx.cls_lua_waf_log, msg)
end

return util
